using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class GameButton : MonoBehaviour
{
    public bool IsDisable = true;
    public Action OnDisableButton;

    private float duration;
    private float length;

    private Animator animator;
    private AnimatorStateInfo animationState;
    private Button button;

    private bool isEnter = false;
    private bool isGetComponent = false;

    public bool IsEnter => isEnter;
    public float AnimProcess => animationState.normalizedTime % 1.0f;

    public void PreInitialze()
    {
        if (!isGetComponent)
        {
            animator = GetComponent<Animator>();
            button = GetComponent<Button>();
            animationState = animator.GetCurrentAnimatorStateInfo(0);
            length = animationState.length;
            isGetComponent = true;
        }

        ClearState();
        ResetAnimation();
    }

    public void ClearState()
    {
        isEnter = false;
        IsDisable = true;
    }

    public void ResetAnimation()
    {
        /*
         * Set the animation clip time point the start of animation,
         * and stop the animation play.
         */
        animator.speed = 0;
        animator.Play(animationState.shortNameHash, 0, 0);
    }

    public void Show(float duration)
    {
        if (!IsDisable)
        {
            return;
        }
        ClearState();
        /*
         * Set the animation play duration by the parameter
         * And set the value `IsDisable` to ensure the button is busy.
         */
        this.duration = duration;
        IsDisable = false;
        animator.speed = length / duration;
        animator.Play(animationState.shortNameHash, 0, 0);
        button.enabled = true;
    }

    public void ButtonUpdate()
    {
        if (IsDisable)
        {
            return;
        }
        duration -= Time.deltaTime;
        animationState = animator.GetCurrentAnimatorStateInfo(0);
        if (animationState.normalizedTime >=  1.0f || duration <= 0.0f)
        {
            DisableButton();
        }

    }

    public void PressEvent()
    {
        isEnter = true;
        DisableButton();
    }

    public void DisableButton()
    {
        IsDisable = true;
        button.enabled = false;
        OnDisableButton();
        ResetAnimation();
    }
}
